import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { List, Avatar, Layout } from 'antd';
import { getPageQuery } from '../../utils/utils';
import LoadingWrapper from '../../components/LoadingWrapper';
import BlankHeader from '../../components/BlankHeader';
import styles from './index.less';

const { Item } = List;

@connect(({ user, loading }) => ({
  userList: user.userList,
  loading: !!(loading.effects['user/fetchFansList'] || loading.effects['user/fetchFollowingList']),
}))
export default class Index extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      urlQuery: getPageQuery(),
    };
  }

  componentDidMount() {
    this.getUserList();
  }

  getUserList = () => {
    const { dispatch } = this.props;
    const { urlQuery } = this.state;

    const type = urlQuery.type === 'fans' ? 'user/fetchFansList' : 'user/fetchFollowingList';

    dispatch({
      type,
      payload: {
        params: {
          uid: urlQuery.uid,
        },
      },
    });
  };

  handleUserIndex = uid => {
    const { history } = this.props;
    history.push(`/pic/user?uid=${uid}`);
  };

  handleGoBack = () => {
    const { history } = this.props;
    history.goBack();
  };

  render() {
    const { userList, loading } = this.props;
    const { urlQuery } = this.state;

    return (
      <Fragment>
        <BlankHeader onClick={this.handleGoBack}>
          {urlQuery.type === 'fans' ? '粉丝' : '关注'}
        </BlankHeader>
        <LoadingWrapper loading={loading} style={{ marginTop: '65px' }}>
          <Layout className={styles.wrapper}>
            <List
              bordered
              itemLayout="horizontal"
              dataSource={userList}
              className={styles.list}
              renderItem={item => (
                <Item onClick={() => this.handleUserIndex(item.id)}>
                  <Item.Meta avatar={<Avatar src={item.avatar} />} title={<a>{item.username}</a>} />
                </Item>
              )}
            />
          </Layout>
        </LoadingWrapper>
      </Fragment>
    );
  }
}
